<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- 操作按钮区域 -->
    <vxe-toolbar size="small" ref="xToolbar">
    <template #buttons>
      <div class='table-operator'>
        <a-button v-has="'commoditymag:add'" @click='handleAdd'>新增</a-button>
        <a-button v-has="'commoditymag:delete'" @click="batchDel">删除</a-button>
        <a-button type="primary" @click="handleExportXls('商品管理')">模板下载</a-button>
        <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader1"
                  :action="importExcelUrl" @change="handleImportExcel">
          <a-button type="primary" >导入</a-button>
        </a-upload>
        <a-button type='primary' v-has="'commoditymag:export'" @click="downExportXls('cnGoods_service')">导出</a-button>

      </div>
    </template>

    </vxe-toolbar>
    <div class="totalView">
      <div class="left">
        <a-input-search v-model="searchOn.classifyName" style="margin-bottom: 8px" placeholder="请输入商品名称" enter-button
                        @search="onSearchs"/>
        <div class="tree-right" :style="'height:'+ (pageHeight-seachHeight-196) +'px;'">
          <a-tree
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :selectedKeys="[queryParam.classifyCode]"
            :checkStrictly="true"
            :replaceFields="{children: 'children', title: 'classifyName', key: 'classifyCode'}"
            style="width:100%;border: 0px;border: none;outline:none;"
            @select="selectNode"
          >
          </a-tree>
        </div>
      </div>

      <div class="right">
        <vxe-grid
          ref="xGrid"
          size="mini"
          :border="true"
          :resizable="true"
          :showOverflow="true"
          :loading="loading"
          :height="pageHeight-seachHeight-132"
          :align="left"
          :columns="columns"
          :data="dataSource"
          :treeConfig="treeConfig"
          @radio-change="radioChangeEvent"
          :radio-config="{ trigger: 'row'}"
        >
          <template #goodsCode='{ row,rowIndex }'>
            <a @click="handleSelect(row)">{{ row.goodsCode }}</a>
          </template>
          <template #action="{ row }">
            <a v-has="'commoditymag:update'" @click='handleEdit(row)'>编辑</a>
            <a-divider type='vertical' />
            <a v-has="'business:log'" href='javascript:' @click='handleBusiness("商品管理",row)'>日志</a>
          </template>
          <template #pager>
            <vxe-pager
              :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
              :currentPage.sync="ipagination.current"
              :page-size.sync="ipagination.pageSize"
              :total="ipagination.total"
              :pageSizes="ipagination.pageSizeOptions"
              @page-change="handlePageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </div>
    <commoditymagModal ref="modalForm" @ok="modalFormOk"></commoditymagModal>
    <business-log ref='businessLog' ></business-log>
  </a-card>
</template>

<script>
  import { getProductCategory } from '@/api/api'
  import commoditymagModal from './modules/CommoditymagModal.vue'
  import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
  import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
  import JInput from '@/components/cn-form/JInput.vue'
  import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import Vue from 'vue'
  import { filterObj } from '@/utils/util'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import { getAction,putAction,postAction } from '@/api/manage'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import search from '@comp/view/base-crud/search/Search'
  import { pick } from 'lodash'
  export default {
    name: 'product-list',
    mixins: [PageListMixin],
    components: {
      FormAddEdit,
      JSuperQuery,
      JInput,
      JTreeSelect,
      search,
      commoditymagModal,
    },
    data() {
      return {
        tokenHeader1: {'Authorization':  'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token},
        description: '商品管理',
        selectedRowKeys: [],
        importExcelUrl: window._CONFIG['domianURL'] + '/goods/cnGoods/importExcel',
        autoExpandParent: true,
        treeData:[],
        searchConfig: [
          {
            // label:'订单编号',
            type: 'input',
            name: 'goodsCode',
            placeholder: '商品编号'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'goodsName',
            placeholder: '商品名称'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'classifyName',
            placeholder: '商品分类'
          },
          {
            type: 'j-select',
            name: 'isSales',
            placeholder: '是否上架',
            dictCode:'je_grounding'
          }
        ],
        //表头
        columns: [],
        //列设置
        settingColumns: [],

        //列定义
        defColumns: [
          { type: 'checkbox', width: 60, fixed: 'left' },
          {
            fixed: 'left',
            title: '商品编号',
            field: 'goodsCode',
            minWidth: 80,
            slots: { default: 'goodsCode' }
          },
          {
            title: '商品名称',
            minWidth: 80,
            field: 'goodsName'
          },
          {
            title: '物料编号',
            field: 'productCode',
            minWidth: 80,
          },
          {
            title: '物料名称',
            minWidth: 80,
            field: 'productName'
          },
          {
            title: '商品分类',
            minWidth: 80,
            field: 'classifyName'
          },
          {
            title: '规格',
            align: 'left',
            ellipsis: true,
            minWidth: 80,
            field: 'goodsSpecifications'
          },
          {
            title: '基本单位',
            minWidth: 80,
            field: 'basicUnitStr',
          },
          {
            title: '建议零售价',
            minWidth: 80,
            field: 'marketingUnitMoney'
          },
          {
            title: '创建人',
            minWidth: 80,
            field: 'createName'
          },
          {
            title: '创建时间',
            minWidth: 80,
            field: 'createTime'
          },
          {
            title: '更新人',
            minWidth: 80,
            field: 'updateName'
          },
          {
            title: '更新时间',
            minWidth: 80,
            field: 'updateTime'
          },
          // {
          //   title: '状态',
          //   field: 'status',
          //   minWidth:80,
          //   fixed: 'right',
          //   slots: { default: 'status' }
          // },
          {
            title: '是否上架',
            field: 'isSales',
            fixed: 'right',
            minWidth: 80,
            width: 80,
            slots: { default: 'update' }
          },
          // {
          //   title: '是否上架',
          //   align: 'center',
          //   field: 'isSales',
          //   fixed: 'right',
          //   width: 120,
          //   scopedSlots: {
          //     // filterIcon: 'filterIcon',
          //     customRender: 'updateStatus'
          //   }
          // },
          {
            title: '操作',
            width: 120,
            fixed: 'right',
            slots: { default: 'action' ,filterDropdown: 'filterDropdown'}
          },
        ],
        url: {
          list: '/goods/cnGoods/findPageList',
          delete: '/goods/cnGoods/deleteByid',
          // detail: '/goods/cnGoods/saveOrUpdate',
          deleteBatch: '/goods/cnGoods/deleteBatch',
          exportXlsUrl: window._CONFIG['domianURL'] + '/goods/cnGoods/exportXls',
          deleteTag: '/cnTerminalController/deleteLabels',
          //组织树
          treeList: window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/findPageList',
          saveOrUpdateTag: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels',
          startOrStopUrl: window._CONFIG['domianURL'] + '/goods/cnGoods/updateGoodsByIsSales',
          // 导入接口
          importExcelUrl: window._CONFIG['domianURL'] + '/goods/cnGoods/importExcel'
        },
      }
    },
    created() {
      this.initColumns()
      this.loadTreeDatas()
      this.$nextTick(() => {
        // 手动将表格和工具栏进行关联
        this.$refs.xGrid.connect(this.$refs.xToolbar)
      })
    },
    methods: {
      startorstop: function(status) {
        if (!this.url.startOrStopUrl) {
          this.$message.error('请设置url启用停用!')
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')

        } else {
          var ids = ''
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          var that = this
          this.$confirm({
            title: '确认修改',
            content: '是否修改选中数据?',
            onOk: function() {
              that.loading = true
              getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
              })
            }
          })
        }
      },
      handleSelect:async function(row) {
        console.log(row)
        this.$refs.modalForm.edit(row)
        this.$refs.modalForm.title='详情'
        this.$refs.modalForm.disableSubmit = true
      },
      handleEdit:async function(row) {
          console.log(row)
        this.$refs.modalForm.edit(row)
        this.$refs.modalForm.isEdit = true
        this.$refs.modalForm.title='编辑'
        this.$refs.modalForm.disableSubmit = false
      },
      selectNode(e, e2) {
        this.queryParam.classifyCode = e[0]
        this.selectedRowKeys = []
        this.selectionRows = []
        this.loadData(1)
      },
      changeStatus(item){
        if(item.isSales==0){
          this.startorstopByid(1,item.id)
        }else{
          this.startorstopByid(0,item.id)
        }
      },
      // 触发onSelect事件时,为部门树右侧的form表单赋值
      setValuesToForm(record) {
        if (record.orgType == '1') {
          this.orgCategoryDisabled = true
        } else {
          this.orgCategoryDisabled = false
        }
        this.$nextTick(() => {
          this.form.getFieldDecorator('fax', { initialValue: '' })
          this.form.setFieldsValue(pick(record, Object.keys(record)))
        })
      },
      search(queryParam, butType) {
        this.selectedRowKeys = []
        this.selectionRows = []
        this.searchOn = {}
        this.queryParam = queryParam
        this.loadData(1)
      },
      modalFormOk() {
        // this.searchOn = ''
        // this.onExpand()
        this.onSearchs()
      },
      onSearchs() {
        this.loadTreeDatas('1')
      },
      //树
      loadTreeDatas(arg) {
        // 加载查询接口
        let datasparams = {}
        if (arg) {
          datasparams = { ...this.searchOn, current: 1 }
        }
        if (!this.url.treeList) {
          this.$message.info('请配置树状接口地址"treeList"')
          return
        }
        postAction(this.url.treeList, datasparams).then(res => {
          console.log(res.result)
          this.treeData = [...res.result.records]
        })
      },
      startorstopByid(isSales,id){
        let that=this
        this.$confirm({
          title: "确认修改",
          content: '是否'+(isSales==0?'下架':'上架')+'选中数据？',
          onOk(){
            that.loading = true;
            postAction(that.url.startOrStopUrl, {id: id, isSales: Number(isSales)}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          },
          onCancel(){
            // that.loadData();
            // that.onClearSelected();
          },
        })
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      getQueryParams() {
        //高级查询器
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

        param.field = this.getQueryField()
        param.current = this.ipagination.current
        param.size = this.ipagination.pageSize
        delete param.birthdayRange //范围参数不传递后台
        return filterObj(param)
      },



      //列设置更改事件
      onColSettingsChange(checkedValues) {
        var key = this.$route.name + ':colsettings'
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      },

      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name + ':colsettings'
        let colSettings = Vue.ls.get(key)
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = []
          this.defColumns.forEach(function(item, i, array) {
            allSettingColumns.push(item.dataIndex)
          })
          this.settingColumns = allSettingColumns
          this.columns = this.defColumns
        } else {
          this.settingColumns = colSettings
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.dataIndex == 'action') {
              return true
            }
            if (colSettings.includes(item.dataIndex)) {
              return true
            }
            return false
          })
          this.columns = cols
        }
      },

      // handleAdd(record) {
      //   let config = {
      //     title: '新增',
      //     width: 500,
      //     addOrUpdateUrl: `${window._CONFIG['domianKaURL']}/kaGrapParam/saveOrUpdate`,  //审核地址
      //     method: 'post',
      //     list: [
      //       {
      //         label: '公司编号',
      //         type: 'input',
      //         placeholder: '公司编号',
      //         name: 'kaCode',  // 后台接受字段
      //         check: { rules: [{ required: true, message: '经销商编号' }] }
      //       },
      //       {
      //         label: '公司名称',
      //         type: 'input',
      //         placeholder: '公司名称',
      //         name: 'fieldName',  // 后台接受字段
      //       },
      //     ]
      //   }
      //   this.$refs.formAdd.edit(record,config )
      //   this.$refs.formAdd.disableSubmit = false
      // },
    },

  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .totalView {
  //margin-top: 8px;
    display: flex;
    flex-direction: row;
  }
  .left {
    border: 1px solid #edeff0;
    min-width: 300px;
    padding: 2px;
  }
  .left-header {
    display: flex;
    justify-content: space-around;
  }
  .left-header-text {
    padding: 5px 0 5px 0;
    width: 100%;
    text-align: center;
    font-size: 18px;
    margin-bottom: 26px;
    background-color: #edeff0;
  }
  .right {
    width: calc(100% - 300px);
  }
</style>